package cn.tjad.tjad2.module.plan.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.qiandian.android.base.common.bean.CommonBean;
import com.qiandian.android.base.widget.TJADTTitleView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import cn.tjad.tjad2.R;
import cn.tjad.tjad2.consts.Keys;
import cn.tjad.tjad2.data.bean.CommonEntity;
import cn.tjad.tjad2.data.bean.FileBean;
import cn.tjad.tjad2.data.bean.Plan;
import cn.tjad.tjad2.data.bean.PlanTask;
import cn.tjad.tjad2.data.bean.Task;
import cn.tjad.tjad2.data.event.PlanTaskEditEvent;
import cn.tjad.tjad2.listener.OnItemClickListener;
import cn.tjad.tjad2.module.common.fragment.RefreshableListFragment;
import cn.tjad.tjad2.module.common.widget.SingleChoicePopupWindow;
import cn.tjad.tjad2.module.plan.adapter.PlanTaskListAdapter;
import cn.tjad.tjad2.net.http.ResponseObserver;
import cn.tjad.tjad2.net.http.RetrofitManager;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.AppUtils;
import cn.tjad.tjad2.utils.DocumentHelper;
import cn.tjad.tjad2.utils.RouteUtils;
import cn.tjad.tjad2.utils.RxUtils;
import cn.tjad.tjad2.utils.Tools;
import io.reactivex.Observable;

@Route(path = PageId.PLAN_TASK_LIST)
public class PlanTaskListFragment extends RefreshableListFragment implements OnItemClickListener, SingleChoicePopupWindow.OnItemClickListener {

//    @BindView(R.id.plan_task_status)
    TextView statusFilterTV;
//    @BindView(R.id.plan_task_delay)
    TextView delayFilterTV;
//    @BindView(R.id.divider_line)
    View divideLine;
    private PlanTaskListAdapter adapter;

    private PlanTask planTask;
    private Task parentTask;
    private Plan plan;
    private List<Task> originData;
    private List<Task> filterData = new ArrayList<>();

    private SingleChoicePopupWindow statusFilterWindow;
    private SingleChoicePopupWindow delayChoiceWindow;

    private final Boolean[] shouldRefresh = new Boolean[1];

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        shouldRefresh[0] = false;
        EventBus.getDefault().register(this);
        Bundle bundle = getArguments();
        if (bundle != null) {
            planTask = (PlanTask) bundle.getSerializable(Keys.PLAN_TASK);
            parentTask = (Task) bundle.getSerializable(Keys.TASK_ITEM);
            plan = (Plan) bundle.getSerializable(Keys.PLAN);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        addHeadView(R.layout.plan_task_filter);
        statusFilterTV = view.findViewById(R.id.plan_task_status);
        delayFilterTV = view.findViewById(R.id.plan_task_delay);
        divideLine = view.findViewById(R.id.divider_line);
        statusFilterTV.setOnClickListener(this::onClick);
        delayFilterTV.setOnClickListener(this::onClick);
        return view;
    }

    @Override
    protected void requestData() {
        if (plan != null) {
            RetrofitManager.getInstance().getApiService()
                .getPlanDetail(Tools.getProjectId(), plan.id)
                .compose(RxUtils.networkTransformer())
                .subscribe(new ResponseObserver<PlanTask>(compositeDisposable) {
                    @Override
                    public void onSuccess(CommonBean<PlanTask> t) {
                        planTask = t.result;
                        originData = planTask.tasks;
                        List<FileBean> fileItems = planTask.fileItems;
                        if (fileItems != null && !fileItems.isEmpty()) {
                            titleView.showRight2(true);
                            titleView.setRightImage2(R.drawable.icon_task_related);
                        } else {
                            titleView.showRight2(false);
                        }
                        doFilter();
                        onDataLoadSuccess(null);
                    }

                    @Override
                    public void onFailed(String message) {
                        Tools.showToast(message);
                        onDataLoadFailed();
                    }
                });
        } else if (parentTask != null) {
            RetrofitManager.getInstance()
                    .getApiService()
                    .getTaskDetail(Tools.getProjectId(), planTask.id, parentTask.id)
                    .compose(RxUtils.networkTransformer())
                    .subscribe(new ResponseObserver<Task>(compositeDisposable) {
                        @Override
                        public void onSuccess(CommonBean<Task> t) {
                            originData = t.result.children;
                            doFilter();
                            onDataLoadSuccess(null);
                        }

                        @Override
                        public void onFailed(String message) {
                            Tools.showToast(message);
                            onDataLoadFailed();
                        }
                    });
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.autoRefresh();
    }

    @Override
    public PlanTaskListAdapter getAdapter() {
        adapter = new PlanTaskListAdapter(filterData);
        adapter.setOnItemClickListener(this);
        adapter.addElementClickListener(R.id.plan_task_item_right_icon, this::onClick);
        return adapter;
    }

    @Override
    protected void setCustomerTitle(TJADTTitleView titleView) {
        super.setCustomerTitle(titleView);
        titleView.showRight(true);
        titleView.setRightImage(R.drawable.icon_message);
    }

    @Override
    public void onTitleClick(int which) {
        super.onTitleClick(which);
        switch (which) {
            case TJADTTitleView.TITLE_RIGHT:
                RouteUtils.toFragmentActivity(getContext(), PageId.MESSAGE_SETTING_MENU, null);
                break;
            case TJADTTitleView.TITLE_RIGHT_2:
                List<FileBean> fileItems = planTask.fileItems;
                if (fileItems != null && !fileItems.isEmpty()) {
                    FileBean fileBean = fileItems.get(0);
                    DocumentHelper.openModelFile(getContext(), fileBean.document, "ppId", planTask.id);
                }
                break;
        }
    }

    @Override
    public void onItemClick(View parentView, View itemView, int position) {
        Task task = adapter.getItemData(position);
        gotoTaskDetail(task);
    }

    private void doFilter() {
        onItemClick(null, null);
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.plan_task_status:
                if (statusFilterWindow == null) {
                    String[] filterElements = AppUtils.getStringArray(R.array.plan_task_filter_status);
                    List<CommonEntity> entities = new ArrayList<>();
                    for (int i = 0; i < filterElements.length; i++) {
                        CommonEntity entity = new CommonEntity();
                        entity.name = filterElements[i];
                        entity.id = i - 1;
                        entities.add(entity);
                    }
                    statusFilterWindow = new SingleChoicePopupWindow(getContext(), entities);
                    statusFilterWindow.setOnItemClickListener(this);
                }
                statusFilterWindow.showAsDropDown(divideLine);
                break;
            case R.id.plan_task_delay:
                if (delayChoiceWindow == null) {
                    String[] filterElements = AppUtils.getStringArray(R.array.plan_task_filter_delay);
                    List<CommonEntity> entities = new ArrayList<>();
                    for (int i = 0; i < filterElements.length; i++) {
                        CommonEntity entity = new CommonEntity();
                        entity.name = filterElements[i];
                        entity.id = i - 1;
                        entities.add(entity);
                    }
                    delayChoiceWindow = new SingleChoicePopupWindow(getContext(), entities);
                    delayChoiceWindow.setOnItemClickListener(this);
                }
                delayChoiceWindow.showAsDropDown(divideLine);
                break;
            case R.id.plan_task_item_right_icon:
                Task task = (Task) view.getTag(R.id.list_item_data);
                if (task != null) {
                    onTaskRightIconClick(task);
                }
                break;
        }
    }

    @Override
    public void onItemClick(SingleChoicePopupWindow window, CommonEntity entity) {
        CommonEntity statusEntity = null;
        if (statusFilterWindow != null) {
            statusEntity = statusFilterWindow.getCheckedEntity();
        } else {
            statusEntity = new CommonEntity();
            statusEntity.id = -1;
        }
        CommonEntity delayEntity = null;
        if (delayChoiceWindow != null) {
            delayEntity = delayChoiceWindow.getCheckedEntity();
        } else {
            delayEntity = new CommonEntity();
            delayEntity.id = -1;
        }
        filterData.clear();
        if (originData != null && originData.size() > 0) {
            CommonEntity finalStatusEntity = statusEntity;
            CommonEntity finalDelayEntity = delayEntity;
            Observable.fromIterable(originData)
                    .filter(task -> {
                        boolean result = true;
                        if (finalStatusEntity.id == -1 && finalDelayEntity.id == -1) {
                            result = true;
                        } else if (finalStatusEntity.id == -1) {
                            result = (task.delay == (finalDelayEntity.id == 1));
                        } else if (finalDelayEntity.id == -1) {
                            result = task.status == finalStatusEntity.id;
                        } else {
                            result = (task.delay == (finalDelayEntity.id == 1)) && (task.status == finalStatusEntity.id);
                        }
                        return result;
                    }).doOnNext(task -> {
                        filterData.add(task);
                    }).doOnComplete(() -> {
                        adapter.notifyDataSetChanged();
            }).subscribe();
        }
    }

    private void onTaskRightIconClick(Task task) {
        if (task.children != null && task.children.size() > 0) {
            Bundle bundle = new Bundle();
            bundle.putString(Keys.TITLE, task.name);
            bundle.putSerializable(Keys.TASK_ITEM, task);
            bundle.putSerializable(Keys.PLAN_TASK, planTask);
            RouteUtils.toFragmentActivity(getContext(), PageId.PLAN_TASK_LIST, bundle);
        } else {
            gotoTaskDetail(task);
        }
    }

    private void gotoTaskDetail(Task task) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(Keys.PLAN_TASK, planTask);
        bundle.putSerializable(Keys.TASK_ITEM, task);
        RouteUtils.toFragmentActivity(getContext(), PageId.PLAN_TASK_DETAIL, bundle);
    }


    @Override
    public void onResume() {
        super.onResume();
        if (shouldRefresh[0]) {
            refreshLayout.autoRefresh();
            shouldRefresh[0] = false;
        }
    }

    @Subscribe
    public void onEvent(PlanTaskEditEvent event) {
        this.shouldRefresh[0] = true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
